/**
 * 
 */
package cn.nawang.ebeim.api.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.nawang.ebeim.api.comm.PageList;
import cn.nawang.ebeim.api.comm.Pages;
import cn.nawang.ebeim.api.domain.Department;
import cn.nawang.ebeim.api.domain.User;
import cn.nawang.ebeim.api.repository.DepartmentRepository;
import cn.nawang.ebeim.api.repository.UserRepository;
import cn.nawang.ebeim.api.repository.impl.DepartmentQueryImpl;
import cn.nawang.ebeim.api.repository.impl.UserQueryImpl;
import cn.nawang.ebeim.api.service.DepartmentService;
import cn.nawang.ebeim.api.utils.ConvertUtil;
import cn.nawang.ebeim.api.utils.Util;

@Service("departmentService")
public class DepartmentServiceImpl implements DepartmentService {

  @Autowired
  private DepartmentQueryImpl departmentQueryImpl;
  @Autowired
  private DepartmentRepository departmentRepository;
  @Autowired
  private UserQueryImpl userQueryImpl;
  @Autowired
  private UserRepository userRepository;
  @Override
  public PageList getDepartmentList(Pages page) {
    PageList pageList = departmentQueryImpl.getDepartmentList(page);
    List<Department> departments = pageList.getObjList();
    pageList.setObjList(this.getDepartmentListLevel(departments));
    return pageList;
  }

  /**
   * 
   * @author fanyb
   * @Description: 获取department树结构列表
   * @param departments
   * @return List<Department> 
   * @date Oct 9, 20159:49:20 AM
   *
   * @修改人 
   * @修改日期
   */
  public List<Department> getDepartmentListLevel(List<Department> departments) {
    if (departments != null && departments.size() > 0) {
      // 解析权限
      // 顺序解析
      // 1.先按照上级编号进行分组
      Map<Integer, List<Department>> resourceMaps = new HashMap<Integer, List<Department>>();
      for (Department department : departments) {
        List<Department> resourceList = null;
        if (!resourceMaps.containsKey(department.getParentId())) {
          // 如果存在key 直接使用
          resourceList = new ArrayList<Department>();
          resourceMaps.put(department.getParentId(), resourceList);
        } else {
          resourceList = resourceMaps.get(department.getParentId());
        }
        // 直接添加到这个目录下
        resourceList.add(department);
      }
      // 2.组织成树
      // 这个遍历放后面 确保MAP中都有东西了
      for (Department department : departments) {
        // 如果存在这个编号 表示一定有下级
        // 组织下级
        if (resourceMaps.containsKey(department.getId())) {
          department.setChildren(resourceMaps.get(department.getId()));
        }
      }
      // 3.这样组织好了后 up_id 是ROOT就是整个结果了
      return resourceMaps.get(0);
    }
    return null;
  }

  @Override
  public boolean saveDept(Department dept, String customerId, String createUserId) {
    try {
      Date d = new Date();
      dept.setCreateTime(d.getTime());
      dept.setCreateUserId(createUserId);
      // dept.setLmTime(d.getTime());
      // dept.setLmUserId(createUserId);
      dept.setCustomerId(customerId);
      dept.setHasChildren((short) 0);
      if (Util.isBlank(dept.getParentId())) {
        dept.setParentId(0);
      }
      if (dept.getParentId() > 0) {
        // 更新上一级部门为有子部门
        Department obj = departmentQueryImpl.findDeptById(dept.getParentId());
        if (obj != null) {
          obj.setHasChildren((short) 1);
          departmentRepository.save(obj);
        }
        dept.setLevel(obj.getLevel() + 1);// 当前部门级别为上一级加1
      } else {
        dept.setLevel(1);// 默认级别为1
      }
      if (Util.isBlank(dept.getIOrder())) {
        dept.setIOrder(0);// 排序默认为0
      }
      departmentRepository.save(dept);
      return true;
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return false;
  }

  @Override
  public Department getDepartmentByName(String name, String customerId) {
    return departmentQueryImpl.findDeptByName(name, customerId);
  }

  @Override
  public Department getDepartmentByNameNotId(String name, int id, String customerId) {
    return departmentQueryImpl.findDeptByNameNotId(name, id, customerId);
  }

  @Override
  public Department getDepartmentById(int departId) {
    Department obj = null;
    try {
      obj = departmentQueryImpl.findDeptById(departId);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return obj;
  }

  @Override
  public boolean delete(int id) {
    
    /** 删除时应判断父节点的是否有孩子，若没有孩子了应把父节点的hasChildren置为0 **/
    Department department = departmentQueryImpl.findDeptById(id);
    departmentQueryImpl.delete(id);
    List<Department> departments = departmentQueryImpl.findDeptByParentid(department.getParentId());
    if (departments == null || departments.isEmpty()) {
      Department parentDepartment = departmentQueryImpl.findDeptById(department.getParentId());
      parentDepartment.setHasChildren((short) 0);
      departmentRepository.save(parentDepartment);     
    }
    /** 删除了该节点的用户，应转到它的父节点下 **/
    List<User> users=userQueryImpl.findByDepartmentId(id);
    if(users!=null&&!users.isEmpty()){
      for(User user:users){
        user.setDepartmentId(department.getParentId());
        userRepository.save(user);
      }
    }
    return true;
  }

  @Override
  public boolean update(Department dept, Department oldObj, String updateUserId) {
    try {
      Date d = new Date();
      dept.setLmUserId(updateUserId);// 修改人编号
      dept.setCreateTime(oldObj.getCreateTime());
      dept.setCreateUserId(oldObj.getCreateUserId());
      dept.setHasChildren(oldObj.getHasChildren());
      dept.setLevel(oldObj.getLevel());
      dept.setParentId(oldObj.getParentId());
      dept.setLmTime(d.getTime());
      departmentRepository.save(dept);
      return true;
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return false;
  }

  @Override
  public String findById(int id) {
    StringBuffer idBuffer=new StringBuffer();
    idBuffer=findIdBuffer(idBuffer,id);
    String idbuff=idBuffer.toString();
    idbuff=idbuff.substring(0,idbuff.lastIndexOf(','));
    String[] idArray=idbuff.split(",");
    String ids=ConvertUtil.toDbString(idArray);
    return ids;
  }
  
  public StringBuffer findIdBuffer(StringBuffer idBuffer,int id){
    Department department = departmentQueryImpl.findDeptById(id);
    idBuffer.append(department.getId()+",");
    //判断是否有子，有子则查询出子的列表
    if(department.getHasChildren()==1){
       List<Department> depts=departmentQueryImpl.findDeptByParentid(department.getId());
       for(Department dept:depts){
         this.findIdBuffer(idBuffer,dept.getId());
       }
    }
    return idBuffer;
  }

}
